package com.epam.weblibrary.controllers;

import com.epam.weblibrary.entities.book.Book;
import com.epam.weblibrary.entities.order.Order;
import com.epam.weblibrary.entities.user.User;
import com.epam.weblibrary.service.order.OrderService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by Iurii_Miedviediev on 9/18/2014.
 */
@Controller
@RequestMapping("/order")
@SessionAttributes({"cart"})
public class OrderController {

    @Autowired
    OrderService orderService;

    @RequestMapping(method = RequestMethod.GET)
    public String displayUserOrders(Model model, @AuthenticationPrincipal User user) {
        model.addAttribute("orders", orderService.findByUser(user));
        return "order/userorders";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String createNewOrder(@AuthenticationPrincipal User user, @ModelAttribute("cart") List<Book> cart) {
        Order newOrder = orderService.createOrder(cart, user);
        cart.clear();
        return "redirect:order/"+newOrder.getId();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String displayOrderDetails(@PathVariable("id") Long id, @AuthenticationPrincipal User user, Model model) {
        model.addAttribute("order", orderService.find(id));
        return "order/details";
    }

    @RequestMapping(value = "/qr/{id}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> renderOrderQrCode(@PathVariable("id") Long id) {
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);

        Order order = orderService.find(id);

        return new ResponseEntity<byte[]>(order.getQrcode(), headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "/{id}", params = "pdf", method = RequestMethod.GET, produces = "application/pdf; charset=utf-8")
    @ResponseBody
    public byte[] generatePdf(@PathVariable("id") Long id) {
        return orderService.createQrPdfDocument(id);
    }
}
